import threading
import time
import datetime
from send.send import send_qq_message
import logging

logger = logging.getLogger(__name__)


def send_worker(remind):
    t = threading.Thread(target=send_thread, args=(remind,))
    t.start()
    # logger.critical(datetime.datetime.now())
    # logger.critical("启动发送线程：提醒id：{}，需要发送的组：".format(remind.id))
    # logger.critical("已启动发送线程，需要发送的组：")
    # logger.critical(remind.groups.all())


def send_thread(remind):
    i = 5
    while i > 0 and not len(remind.groups.all()):
        time.sleep(1)
        i -= 1
        if i == 0:
            logger.critical("该提醒没有小组！")
            return
    uid_list = list()
    for group in remind.groups.all():
        for member in group.members.all():
            if member.id in uid_list:
                continue
            uid_list.append(member.id)
            name = member.first_name
            qq = member.information.all().first().qq
            owner = remind.owner.first_name
            event = remind.event
            end_time = remind.time
            message = "尊敬的<{}>，你有一条提醒需要完成。创建人<{}>，内容：<{}>，截止时间<{}>.".format(name, owner, event, end_time)
            send_qq_message(qq, message)
